package com.ssm.filter;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

        String[] passUrls={"/login","/js","/css","/image","/plugins","build","/valid","logout"};
        String uri = httpServletRequest.getRequestURI();
        String url = httpServletRequest.getServletPath();
        for(String p:passUrls){
            if(url.startsWith(p)){
                filterChain.doFilter(httpServletRequest, httpServletResponse);
                return;
            }
        }
        HttpSession session = httpServletRequest.getSession();
        if(session.getAttribute("type")==null){
            httpServletResponse.sendRedirect("/login");
        }else {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }
        return;
    }
}
